package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author jack
 * @data 2023 9:21
 */
@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Autowired
    private CacheService cacheService;

    /**
     * 查询所有频道数据
     * tips: 使用redis优化性能
     *
     * @return
     */
    @Override
    public ResponseResult channels() {
        //1. 先查缓存有没有
        String chennelsJSON = cacheService.get("chennels");

        //2. 缓存有：直接返回
        if (!StringUtils.isEmpty(chennelsJSON)){
            List<WmChannel> lists = JSON.parseArray(chennelsJSON, WmChannel.class);
            return ResponseResult.okResult(lists);
        }else {
            //3. 缓存没有：查询数据库,并将查到的结果添加到缓存
            List<WmChannel> list = list();
            cacheService.set("chennels",JSON.toJSONString(list));
            return ResponseResult.okResult(list);
        }
    }
}
